package net.bcxuexi.socket.stream.inhandle;

import net.bcxuexi.config.Config;
import net.bcxuexi.exception.MyException;
import net.bcxuexi.socket.SocketManager;
import net.bcxuexi.socket.model.SocketModel;
import net.bcxuexi.socket.stream.StreamData;
import net.bcxuexi.socket.stream.outwrap.OutputDataWrap;
import net.bcxuexi.tools.MyLog;

/**
 * 内网服务器发送过来的数据处理
 */
public class InnerInputStreamHandler extends AbstractInputStreamHandler {

	public InnerInputStreamHandler() {
	}

	@Override
	public void handle() {
		StreamData streamData = null;// 待处理数据

		if (streamData == null) {
			try {
				streamData = take();// 从阻塞队列中取数据，可能会被阻塞
			} catch (InterruptedException e) {
				// 没有取到数据
				return;
			}
		}

		if (streamData == null) {
			MyLog.info("InnerInputStreamHandler队列为空，休息！");
			return;
		}
		// 数据处理
		process(streamData);
		try {
			sleep(80);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 数据信息封装，添加头部再发送数据给服务端。
	 * 
	 * @param streamData
	 */
	public void process(StreamData streamData) {
		if (Config.debug) {
			String msg = new String(streamData.data, 0, streamData.total);
			MyLog.info("接收到内网服务器信息：" + msg);
		}
		// 查找当前innersocket对应的data通信socket
		String innerIp = streamData.getSocketModel().getInnerIp();
		int innerPort = streamData.getSocketModel().getInnerPort();
		String proxyConnId = streamData.getSocketModel().getProxyConnId();
		//得到在发送proxyConnId数据的socket
		SocketModel dataSocketModel = SocketManager.getInstance().getDataSocketByProxyConnId(proxyConnId);
		
		try {
			// 封装消息
			OutputDataWrap outputDataWrap = new OutputDataWrap();
			StreamData dataStreamData = outputDataWrap.csDataWrap(streamData,
					streamData.getSocketModel().getProxyConnId(), streamData
							.getSocketModel().getInnerIp(), streamData
							.getSocketModel().getInnerPort());
			dataStreamData.setSocketModel(dataSocketModel);
			if(Config.debug){
				String wdata = new String(dataStreamData.data,0,dataStreamData.total);
				MyLog.info("内网服务器信息添加头部后的数据："+wdata);
			}
			try {
				// 发送消息
				dataSocketModel.getWriteStream()
						.addData(dataStreamData);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} catch (MyException e) {
			MyLog.info(e.msg);
		}
	}

}
